package com.maingel.showcase.as;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.maingel.showcase.event.TimerEvent;

import de.greenrobot.event.EventBus;

public class TimerService extends Service {
    private Thread timerThread;

    @Override
    public void onCreate() {
        Log.v("onCreate: ", Thread.currentThread().getName());
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.v("onStartCommand: ", Thread.currentThread().getName());

        timerThread = new Thread(new Runnable() {
            private int index = 0;

            @Override
            public void run() {
                try {
                    while (index < 3) {
                        index++;
                        Thread.sleep(3000);
                        Log.v("Index: ", Thread.currentThread().getName() + "......" + index);
                        EventBus.getDefault().post(new TimerEvent(index + ""));
                    }
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                EventBus.getDefault().post(new TimerEvent("-1"));
                stopSelf();
            }
        });
        timerThread.start();
        return START_REDELIVER_INTENT;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.v("onDestroy: ", Thread.currentThread().getName());
        if(timerThread != null) {
            timerThread.interrupt();
            timerThread = null;
        }
    }
}
